package taller2.view.components;

import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;

import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

import taller2.utils.Utils;

public class MyHighlighter {
    private Highlighter highlight;
    private JTextArea textArea;
    private DefaultHighlighter.DefaultHighlightPainter painter;
    private int posHighlight;
    
    public MyHighlighter(JTextArea textArea){
    	 this.posHighlight = 0;
         this.textArea = textArea;
    	 this.painter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);
    	 this.highlight = textArea.getHighlighter();
    }
    
    public void reset(){
    	posHighlight = 0;
    	unHighlight();
    }
    
    // counts the amount of \n in a string
    private int countLines(String str) {
        int lines = 1;
        int pos = 0;
        while ((pos = str.indexOf("\n", pos) + 1) != 0) {
            lines++;
        }
        return lines;
    }      
   
    // returns a substring containing the line
    public String getLine(String str,int line){
        int index=0;
        int cont=0;
        while( (index != -1) && (cont != line)){
        	index = str.indexOf("\n",index+1);
        	cont++;
        }
           
        int start = index;
        int end = str.indexOf("\n",index+1);

        try{
			return str.substring(start, end).replaceFirst("\\s+", "");  // the last one deletes indentation
		}catch(StringIndexOutOfBoundsException e){
			return str;
		}
    }
   
    // highlights a line in a textArea
    public void highlightLine(int line){
         try {
        	 posHighlight = line;
             highlight.addHighlight(textArea.getLineStartOffset(line), textArea.getLineEndOffset(line),painter);
             textArea.setCaretPosition(textArea.getLineStartOffset(line));
             centerLineInScrollPane();
         } catch (BadLocationException e) {
         	e.printStackTrace();
         }
    }
   
    // removes all highlight from the textArea
    public void unHighlight(){
    	highlight.removeAllHighlights();
    }
    
 // highlights sequentially ignoring whitespaces and returns new highlighted line, autoscrolls text when necessary
    public String highlightNextLine(){
    	String code = textArea.getText();
    	
    	if((posHighlight+1) < countLines(code)){
    		highlightLine(posHighlight);
		}else{                                 // resets scrollbar's position if it reached the end
			reset();
			return "";
		}
    	
    	String line = getLine(code,posHighlight);
    	posHighlight++;
    	
    	return line;
    }
 
    // highlights sequentially ignoring whitespaces and returns new highlighted line, autoscrolls text when necessary
    public String highlightPrevLine(){
    	String code = textArea.getText();
    	
        if((posHighlight-1) > 0 ){                                              // does nothing if first line
            posHighlight--;
            String line = getLine(code,posHighlight-1);
           
            highlightLine(posHighlight-1);
            centerLineInScrollPane();
            return line;
        }
   
    return "";
    }
    
    // Attempts to centers the line containing the caret at the center of the scroll pane.
   public void centerLineInScrollPane(){
           Container container = SwingUtilities.getAncestorOfClass(JViewport.class, textArea);

           if (container == null)
                   return;
           try{
                   Rectangle r = textArea.modelToView(textArea.getCaretPosition());
                   JViewport viewport = (JViewport)container;
                   int extentHeight = viewport.getExtentSize().height;
                   int viewHeight = viewport.getViewSize().height;

                   int y = Math.max(0, r.y - (extentHeight / 2));
                   y = Math.min(y, viewHeight - extentHeight);

                   if(viewport != null)
                	   viewport.setViewPosition(new java.awt.Point(0,y));
           }
           catch(BadLocationException e) {}
   }

   // AVISO, ESTO ESTA HARCODEADO PARA UNA MATRIZ DE FLOYD...
   public void highlightWord(int higlightedWordNumber) {
	   String code = textArea.getText();
	   int higlightedWordStart = Utils.getStartingPosition(code,higlightedWordNumber,"[");
	   if(higlightedWordStart > 0){
		   int higlightedWordend = code.indexOf("]", higlightedWordStart) + 1;
	         
		   try {
			   highlight.addHighlight(higlightedWordStart,higlightedWordend,painter);
		   } catch (BadLocationException e) {
			   e.printStackTrace();
		   }
	   }
   }    
}
